/**
 * 删除链表的倒数第 N 个结点
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode cur = head;
        int sz = 0;
        if (head.next == null) {
            return null;
        }
        if (n == 1) {
            while (cur.next.next != null) {
                cur = cur.next;
            }
            cur.next = null;
            return head;
        }
        while (cur != null) {
            cur = cur.next;
            sz++;
        }
        cur = head;
        if (n == sz) {
            head = head.next;
            return head;
        }
        int index = sz - n;
        while (--index > 0) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        return head;
    }
}